import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../../controllers/emotion_controller.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_text_styles.dart';
import '../../core/constants/app_constants.dart';
import '../../core/constants/emotion_constants.dart';
import '../../core/utils/app_utils.dart';
import '../../core/routes/app_routes.dart';
import '../widgets/emotion_selector_widget.dart';
import '../widgets/quick_record_widget.dart';
import '../widgets/daily_summary_widget.dart';
import '../layouts/main_layout.dart';

/// 首页界面
/// Home page with emotion selector, quick record and daily summary
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  late AnimationController _animationController;
  
  final EmotionController _emotionController = Get.find<EmotionController>();
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    
    _animationController.forward();
    _loadData();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  /// 加载数据
  /// Load data
  Future<void> _loadData() async {
    await _emotionController.loadTodayRecords();
    await _emotionController.loadStatistics();
  }

  /// 刷新数据
  /// Refresh data
  Future<void> _onRefresh() async {
    await _loadData();
  }

  /// 处理情绪选择
  /// Handle emotion selection
  void _onEmotionSelected(String emotionType, int intensity) {
    AppRoutes.toRecord(
      emotionType: emotionType,
      intensity: intensity,
    );
  }

  /// 处理快速记录
  /// Handle quick record
  void _onQuickRecord(String emotionType) {
    AppRoutes.toRecord(emotionType: emotionType);
  }

  @override
  Widget build(BuildContext context) {
    return MainLayout(
      currentIndex: 0,
      appBarTitle: '情绪记录',
      child: RefreshIndicator(
        onRefresh: _onRefresh,
        color: AppColors.primary,
        child: CustomScrollView(
          slivers: [
            // 问候语区域
            // Greeting section
            SliverToBoxAdapter(
              child: _buildGreetingSection(),
            ),
            
            // 主要内容
            // Main content
            SliverToBoxAdapter(
              child: Padding(
                padding: EdgeInsets.all(16.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 情绪选择器
                    // Emotion selector
                    _buildEmotionSelectorCard(),
                    
                    SizedBox(height: 24.h),
                    
                    // 快速记录
                    // Quick record
                    _buildQuickRecordCard(),
                    
                    SizedBox(height: 24.h),
                    
                    // 今日总结
                    // Daily summary
                    _buildDailySummaryCard(),
                    
                    SizedBox(height: 24.h),
                    
                    // 最近记录
                    // Recent records
                    _buildRecentRecordsCard(),
                    
                    SizedBox(height: 32.h),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建问候语区域
  /// Build greeting section
  Widget _buildGreetingSection() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            AppColors.primary.withOpacity(0.1),
            AppColors.secondary.withOpacity(0.1),
          ],
        ),
      ),
      child: _buildGreeting(),
    );
  }

  /// 构建问候语
  /// Build greeting
  Widget _buildGreeting() {
    final hour = DateTime.now().hour;
    String greeting;
    IconData greetingIcon;
    
    if (hour < 6) {
      greeting = '夜深了，注意休息';
      greetingIcon = Icons.bedtime;
    } else if (hour < 12) {
      greeting = '早上好';
      greetingIcon = Icons.wb_sunny;
    } else if (hour < 18) {
      greeting = '下午好';
      greetingIcon = Icons.wb_sunny_outlined;
    } else {
      greeting = '晚上好';
      greetingIcon = Icons.nights_stay;
    }
    
    return Row(
      children: [
        Icon(
          greetingIcon,
          color: AppColors.primary,
          size: 24.sp,
        ),
        SizedBox(width: 8.w),
        Text(
          greeting,
          style: AppTextStyles.headlineSmall.copyWith(
            color: AppColors.textPrimary,
            fontWeight: FontWeight.w600,
            fontSize: 20.sp,
          ),
        ),
      ],
    );
  }

  /// 构建今日总结卡片
  /// Build daily summary card
  Widget _buildDailySummaryCard() {
    return Card(
      elevation: 2,
      shadowColor: AppColors.shadowColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(AppConstants.radiusLarge),
      ),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(AppConstants.radiusLarge),
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              AppColors.primary.withOpacity(0.05),
              AppColors.secondary.withOpacity(0.02),
            ],
          ),
        ),
        child: const Padding(
          padding: EdgeInsets.all(AppConstants.paddingMedium),
          child: DailySummaryWidget(),
        ),
      ),
    );
  }

  /// 构建情绪选择器卡片
  /// Build emotion selector card
  Widget _buildEmotionSelectorCard() {
    return Card(
      elevation: 2,
      shadowColor: AppColors.shadowColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(AppConstants.radiusLarge),
      ),
      child: Padding(
        padding: const EdgeInsets.all(AppConstants.paddingMedium),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.psychology_outlined,
                  color: AppColors.primary,
                  size: 24,
                ),
                const SizedBox(width: AppConstants.spacingSmall),
                Text(
                  '现在的心情如何？',
                  style: AppTextStyles.titleMedium.copyWith(
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
            const SizedBox(height: AppConstants.spacingMedium),
            EmotionSelectorWidget(
              onEmotionSelected: _onEmotionSelected,
              showIntensitySlider: false,
            ),
          ],
        ),
      ),
    );
  }

  /// 构建快速记录卡片
  /// Build quick record card
  Widget _buildQuickRecordCard() {
    return Card(
      elevation: 2,
      shadowColor: AppColors.shadowColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(AppConstants.radiusLarge),
      ),
      child: Padding(
        padding: const EdgeInsets.all(AppConstants.paddingMedium),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.flash_on_outlined,
                  color: AppColors.accent,
                  size: 24,
                ),
                const SizedBox(width: AppConstants.spacingSmall),
                Text(
                  '快速记录',
                  style: AppTextStyles.titleMedium.copyWith(
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
            const SizedBox(height: AppConstants.spacingMedium),
            QuickRecordWidget(
              onQuickRecord: _onQuickRecord,
            ),
          ],
        ),
      ),
    );
  }

  /// 构建最近记录卡片
  /// Build recent records card
  Widget _buildRecentRecordsCard() {
    return Obx(() {
      final todayRecords = _emotionController.todayRecords;
      
      return Card(
        elevation: 2,
        shadowColor: AppColors.shadowColor,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(AppConstants.radiusLarge),
        ),
        child: Padding(
          padding: const EdgeInsets.all(AppConstants.paddingMedium),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Icon(
                        Icons.history,
                        color: AppColors.secondary,
                        size: 24,
                      ),
                      const SizedBox(width: AppConstants.spacingSmall),
                      Text(
                        '今日记录',
                        style: AppTextStyles.titleMedium.copyWith(
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ],
                  ),
                  if (todayRecords.isNotEmpty)
                    TextButton(
                      onPressed: () => AppRoutes.toHistory(),
                      child: Text(
                        '查看全部',
                        style: AppTextStyles.bodyMedium.copyWith(
                          color: AppColors.primary,
                        ),
                      ),
                    ),
                ],
              ),
              const SizedBox(height: AppConstants.spacingMedium),
              
              if (todayRecords.isEmpty)
                _buildEmptyRecords()
              else
                _buildRecentRecordsList(todayRecords),
            ],
          ),
        ),
      );
    });
  }

  /// 构建空记录状态
  /// Build empty records state
  Widget _buildEmptyRecords() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(
        vertical: AppConstants.paddingLarge,
      ),
      child: Column(
        children: [
          Icon(
            Icons.sentiment_neutral,
            size: 48,
            color: AppColors.textSecondary,
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          Text(
            '今天还没有记录',
            style: AppTextStyles.bodyLarge.copyWith(
              color: AppColors.textSecondary,
            ),
          ),
          const SizedBox(height: AppConstants.spacingSmall),
          Text(
            '点击上方情绪按钮开始记录吧',
            style: AppTextStyles.bodyMedium.copyWith(
              color: AppColors.textTertiary,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建最近记录列表
  /// Build recent records list
  Widget _buildRecentRecordsList(List<dynamic> records) {
    return Column(
      children: records.take(3).map((record) {
        final emotionType = record['emotion_type'] as String;
        final intensity = record['intensity'] as int;
        final content = record['content'] as String?;
        final createdAt = DateTime.parse(record['created_at'] as String);
        
        return Container(
          margin: const EdgeInsets.only(bottom: AppConstants.spacingSmall),
          padding: const EdgeInsets.all(AppConstants.paddingMedium),
          decoration: BoxDecoration(
            color: EmotionConstants.getEmotionColor(emotionType).withOpacity(0.1),
            borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
            border: Border.all(
              color: EmotionConstants.getEmotionColor(emotionType).withOpacity(0.3),
              width: 1,
            ),
          ),
          child: InkWell(
            onTap: () => AppRoutes.toRecordDetail(record['id'] as String),
            borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
            child: Row(
              children: [
                // 情绪图标
                // Emotion icon
                Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: EmotionConstants.getEmotionColor(emotionType),
                    borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                  ),
                  child: Icon(
                    EmotionConstants.getEmotionIcon(emotionType),
                    color: Colors.white,
                    size: 20,
                  ),
                ),
                
                const SizedBox(width: AppConstants.spacingMedium),
                
                // 记录信息
                // Record info
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            EmotionConstants.getEmotionLabel(emotionType),
                            style: AppTextStyles.titleSmall.copyWith(
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          const SizedBox(width: AppConstants.spacingSmall),
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 6,
                              vertical: 2,
                            ),
                            decoration: BoxDecoration(
                              color: EmotionConstants.getEmotionColor(emotionType).withOpacity(0.2),
                              borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                            ),
                            child: Text(
                              '$intensity',
                              style: AppTextStyles.bodySmall.copyWith(
                                color: EmotionConstants.getEmotionColor(emotionType),
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ],
                      ),
                      if (content != null && content.isNotEmpty) ...[
                        const SizedBox(height: 4),
                        Text(
                          AppUtils.truncateText(content, 50),
                          style: AppTextStyles.bodySmall.copyWith(
                            color: AppColors.textSecondary,
                          ),
                        ),
                      ],
                      const SizedBox(height: 4),
                      Text(
                        AppUtils.formatTime(createdAt),
                        style: AppTextStyles.bodySmall.copyWith(
                          color: AppColors.textTertiary,
                        ),
                      ),
                    ],
                  ),
                ),
                
                // 箭头图标
                // Arrow icon
                Icon(
                  Icons.chevron_right,
                  color: AppColors.textTertiary,
                  size: 20,
                ),
              ],
            ),
          ),
        );
      }).toList(),
    );
  }


}